package l1j.server.server.model.trade;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import l1j.server.Config;
import l1j.server.L1DatabaseFactory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_TradeStatus;
import l1j.server.server.utils.SQLUtil;

public class L1TradePair {
	L1PcInstance pc_1;
	L1PcInstance pc_2;

	public L1TradePair(L1PcInstance pc_1, L1PcInstance pc_2) {
		this.pc_1 = pc_1;
		this.pc_2 = pc_2;
	}

	public L1PcInstance getPartner(L1PcInstance pc) {
		return pc_1.getId() == pc.getId() ? pc_2 : pc_1;
	}

	public void deal() {
		for (L1ItemInstance items : pc_1.getTradeWindowInventory().getItems()) {
			pc_1.getTradeWindowInventory().tradeItem(items, items.getCount(),
					pc_2.getInventory());
			logTrade(items.getId(), items.getName() + items.getLogName(),
					items.getCount(), pc_1, pc_2);
		}
		for (L1ItemInstance items : pc_2.getTradeWindowInventory().getItems()) {
			pc_2.getTradeWindowInventory().tradeItem(items, items.getCount(),
					pc_1.getInventory());
			logTrade(items.getId(), items.getName() + items.getLogName(),
					items.getCount(), pc_2, pc_1);
		}
		pc_1.sendPackets(new S_TradeStatus(0));
		pc_2.sendPackets(new S_TradeStatus(0));
		pc_1.setTradeOk(false);
		pc_2.setTradeOk(false);
		pc_1.setTradeID(0);
		pc_2.setTradeID(0);
		pc_1.turnOnOffLight();
		pc_2.turnOnOffLight();
	}

	public void stopTrade() {
		for (L1ItemInstance items : pc_1.getTradeWindowInventory().getItems()) {
			pc_1.getTradeWindowInventory().tradeItem(items, items.getCount(),
					pc_1.getInventory());
		}
		for (L1ItemInstance items : pc_2.getTradeWindowInventory().getItems()) {
			pc_2.getTradeWindowInventory().tradeItem(items, items.getCount(),
					pc_2.getInventory());
		}
		pc_1.sendPackets(new S_TradeStatus(1));
		pc_2.sendPackets(new S_TradeStatus(1));
		pc_1.setTradeOk(false);
		pc_2.setTradeOk(false);
		pc_1.setTradeID(0);
		pc_2.setTradeID(0);
	}

	private void logTrade(int itemObj, String item_name, int item_count,
			L1PcInstance from, L1PcInstance to) {
		if (!Config.writeTradeLog)
			return;
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con
					.prepareStatement("INSERT INTO log_trade SET time=?,item_name=?,item_count=?,fromname=?,toname=?,itemobj=?,fromobj=?,toobj=?");
			pstm.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
			pstm.setString(2, item_name);
			pstm.setInt(3, item_count);
			pstm.setString(4, from.getName());
			pstm.setString(5, to.getName());
			pstm.setInt(6, itemObj);
			pstm.setInt(7, from.getId());
			pstm.setInt(8, to.getId());
			pstm.execute();
		} catch (SQLException e) {
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
}
